import { View, Button, Image, Input } from "@tarojs/components";
import { useEffect, useState } from "react";

import { callContainerPost, useCallContainerGet } from "@/tools/useCallContainer";
import Taro from "@tarojs/taro";
import TabBar from '@/components/TabBar';
import './index.scss';
import { styled } from "@linaria/react";

export default function UserIndex() {
    const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
    
    const [{collect_count, likes_count, dislike_count, tagRank}] = useCallContainerGet('/users/_open_id/report');
    
    const [{ userinfo }] = useCallContainerGet('/users/_open_id/getinfo');
    const { u_name, u_image } = userinfo ?? {};

    // Use state to manage your component's local state
    const [avatarUrl, setAvatarUrl] = useState(u_image || defaultAvatarUrl);
    const [inputValue, setInputValue] = useState(u_name);

    // useEffect to handle asynchronous data fetching
    useEffect(() => {
        // Check if u_name and u_image are available
        if (u_name !== undefined && u_image !== undefined) {
            setAvatarUrl(u_image || defaultAvatarUrl);
            setInputValue(u_name);
        }
    }, [u_name, u_image]); // useEffect will run whenever u_name or u_image changes

    const onChooseAvatar = async (e) => {
        const { avatarUrl } = e.detail;
        setAvatarUrl(avatarUrl);
        console.log(e.detail);
        let cloudPath = 'userPhoto/' + Date.now() + '.jpg';
        
        try {
            console.log('开始上传文件',avatarUrl);
            const { fileID } = await wx.cloud.uploadFile({
                cloudPath: cloudPath, // 这个文件地址可以换成动态的
                filePath: avatarUrl
            })
            console.log('上传成功，开始转换',fileID);
            if(fileID != undefined){
                let imgUrl = fileID;
                setAvatarUrl(imgUrl);
                callContainerPost('/users/_open_id/image', {"image":imgUrl}).then();
                console.log(imgUrl);
            }
        }
        catch (error) {
            Taro.showToast({
                icon: 'error',
                title: '图片太大, 请重新选择!'
            });
        }
    }
    
    const onNameBlur = (e) => {
        let nickName = e.detail.value;
        console.log(nickName);
        if (nickName.length <= 3) {
            Taro.showToast({
                icon: 'error',
                title: '名字过短,至少4个字符'
            })
            return;
        }
        if (nickName.length > 15) {
            Taro.showToast({
                icon: 'error',
                title: '名字过长,超过15个字符'
            })
            return;
        }
        callContainerPost('/users/_open_id/name', {"name":nickName}).then();
    }

    const [currentTab, setCurrentTab] = useState<number>(3);

    const handleTabClick = (index: number) => {
        setCurrentTab(index);
        if (index === 0) {
            Taro.redirectTo({ url: '../index/index' });
            //Taro.navigateTo({ url: '../index/index' });
        } else if (index === 1) {
            Taro.redirectTo({ url: '../GetMapp/index' });
            //Taro.navigateTo({ url: "../restaurant/index?id=1" });
        }
        else if (index === 2) {
            Taro.redirectTo({ url: '../collections/index' });
            //Taro.navigateTo({ url: "../restaurant/index?id=1" });
        }
        else if (index === 3) {
            //Taro.redirectTo({ url: "../Users/index" });
            //Taro.navigateTo({ url: "../collections/index" });
        }
        // 添加其他导航项的处理逻辑
    };
    const tabList = [
    { title: '食堂', iconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/home1.png', selectedIconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/home2.png' },
    { title: '地图', iconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/map_marker_icon.svg' , selectedIconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/map_marker_icon.svg'},
    { title: '收藏', iconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/collection1.png', selectedIconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/collection2.png'},
    
    { title: '用户', iconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/user_circle_light_icon.png', selectedIconPath: 'cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/8726547_user_circle_icon.png'},
    // 添加其他的导航项
    ];

    return (
        <View>
            <View style={{padding:"10px", borderBottom:"1px solid #dadada"}}>
                <Button className="avatar" openType="chooseAvatar" onChooseAvatar={onChooseAvatar} style={{}}>
                    <Image src={avatarUrl} mode="aspectFit"></Image>
                </Button>
                <Input type="nickname" value={inputValue} className="weui-input" placeholder="请输入昵称" onBlur={onNameBlur} style={{textAlign:"center", backgroundColor:"transparent"}}/>
            </View>
            
            <View className="reportContainer">
                <View className="reportItem">
                    <Image className="imgico" src="cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/star_favorite_award_like_icon.png" mode="aspectFit"></Image>
                    <View>收藏数量</View>
                    <View>{collect_count}</View>
                </View>
                <View className="reportItem">
                    <Image className="imgico" src="cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/heart_love_romance_like_icon.png" mode="aspectFit"></Image>
                    <View>点赞数量</View>
                    <View>{likes_count}</View>
                </View>
                <View className="reportItem">
                    <Image className="imgico" src="cloud://prod-0g6virbea3062996.7072-prod-0g6virbea3062996-1322280255/tabbar/cross_delete_remove_cancel_icon.png" mode="aspectFit"></Image>
                    <View>点踩数量</View>
                    <View>{dislike_count}</View>
                </View>
            </View>
            <View style={{display:"block", margin :"10px auto 30px auto", width:"90%", border:"1px solid #dadada", borderRadius:"10px", boxShadow: "0 0 4px rgba(0,0,0,.35)"}}>
                <View className="textView" style={{}}>
                    您的口味偏好排名
                </View>
                <View className="tagRankContainer">
                    {
                        (tagRank ?? []).map((tag, index)=>(
                                <View style={{width:"100%", height:"30px", display:"block", padding:"2px 0 2px 40px"}}>
                                    <DishTag key={index} style={{float:"left", width:"30px",backgroundColor:tag.tag_likes>=0?"#ff7837d1":"#31c27c"}}>{tag.tag_name}</DishTag>
                                    <View style={{width:"60%",float:"left", marginLeft:"10px"}}>共获得您的{tag.tag_likes>=0?tag.tag_likes:-tag.tag_likes}次点{tag.tag_likes>=0?"赞":"踩"}</View>
                                </View>
                            )
                        )
                    }
                </View>
            </View>
            
            <View className="container"> 
                <TabBar tabList={tabList} current={currentTab} onClick={handleTabClick} />
            </View>
        </View>
        
    );
}
const DishTag = styled(View)`
  padding: 5px 10px;
  height: fit-content;
  border-radius: 10px;
  background-color: #ff7837d1;
  color: white;
  font-size: 24px;
  margin-right: 10px;
`;